/* eslint-disable no-console, no-unused-vars */
/* global chrome */
class TabRefresher {
  constructor() {
    this.socket = null
    this.pendingTabs = new Map()
    this.refreshTabs = 0
    this.refreshedTabs = 0
    this.reconnectAttempts = 0
    this.MAX_ATTEMPTS = 5
    this.initWebSocket()
    this.setupListeners()
  }

  initWebSocket() {
    this.socket = new WebSocket('ws://localhost:8080/plugin')

    this.socket.onopen = () => {
      this.reconnectAttempts = 0
      console.log('[plugin] 已连接服务端')
    }

    this.socket.onmessage = async (event) => {
      try {
        const { type, urls } = JSON.parse(event.data)
        if (type === 'REFRESH_TAB') {
          await Promise.all(urls.map(url => this.handleRefreshCommand(url)))
        }
      }
      catch (e) {
        console.error('[plugin] 消息解析失败:', e)
      }
    }

    this.socket.onclose = () => {
      if (this.reconnectAttempts < this.MAX_ATTEMPTS) {
        const delay = Math.min(3000 * ++this.reconnectAttempts, 15000)
        window.setTimeout(() => this.initWebSocket(), delay)
      }
    }
  }

  setupListeners() {
    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
      if (tab.url && tab.url.includes('link.csdn.net')) {
        chrome.tabs.remove(tabId)
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          if (tabs[0]) {
            chrome.tabs.sendMessage(tabs[0].id, {
              action: 'showMessage',
              message: '已自动关闭CSDN安全中心页面',
            })
          }
        })
      }

      if (!this.pendingTabs.has(tabId))
        return

      if (changeInfo.status === 'complete') {
        const { url, title, startTime } = this.pendingTabs.get(tabId)
        const elapsed = (Date.now() - startTime) / 1000
        console.log(`[plugin] \u001B[1;32m刷新完成\u001B[0m ${url} (耗时: ${elapsed.toFixed(2)}s)`)

        this.refreshedTabs++
        this.socket?.send(JSON.stringify({
          type: 'REFRESH_RESULT',
          url,
          title,
          success: true,
          last: this.refreshedTabs === this.refreshTabs,
        }))

        this.pendingTabs.delete(tabId)
      }
    })
  }

  async handleRefreshCommand(urlPattern) {
    console.log(`[plugin] \u001B[1;36m收到『刷新』指令: ${urlPattern}\u001B[0m`)

    const tabs = await new Promise(resolve =>
      chrome.tabs.query({ url: urlPattern }, resolve),
    )

    if (tabs.length === 0) {
      this.socket?.send(JSON.stringify({
        type: 'REFRESH_RESULT',
        url: urlPattern,
        success: false,
        reason: '未找到匹配标签页',
      }))
      return
    }

    tabs.forEach((tab) => {
      // 标题截取
      const maxLength = 30
      const displayTitle = tab.title?.length > maxLength
        ? `${tab.title.substring(0, maxLength)}...`
        : tab.title
      this.pendingTabs.set(tab.id, {
        url: tab.url,
        title: displayTitle,
        startTime: Date.now(),
      })

      chrome.tabs.reload(tab.id)
      console.log(`[plugin] 开始刷新: ${displayTitle} (${tab.url})`)
    })
    this.refreshTabs += tabs.length
  }
}

// eslint-disable-next-line unused-imports/no-unused-vars
const tabRefresher = new TabRefresher()
